<?php
declare (strict_types=1);

namespace app\technician_api\controller;

use Throwable;
use ba\ClickCaptcha;
use think\facade\Config;
use think\facade\Validate;
use app\common\facade\Token;
use app\admin\model\AdminLog;
use app\common\controller\Technician;
use think\facade\Db;

class Order extends Technician
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = ['*'];
    protected $model;

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Order;
    }

    // 技师接单
    public function taking (): void
    {
        $params = $this->request->param();
        $find = $this->model
            ->where([
                'id' => $params['id']
            ])
            ->find();
        if (!$find) {
            $this->error("订单异常");
        }
        if ($find['order_state'] != "Paid") {
            $this->error("订单异常");
        }
        $find->order_state = 'Received';
        $find->save();
        setOrderStateLog($find['id'], 'Received');
        $this->success('接单成功');
    }

    // 技师取消接单
    public function canceled ()
    {
        $params = $this->request->param();
        $find = $this->model
            ->where([
                'id' => $params['id']
            ])
            ->find();
        if (!$find) {
            $this->error("订单异常");
        }
        if ($find['order_state'] != "Paid") {
            $this->error("订单异常");
        }
        $find->order_state = 'Canceled';
        $find->save();
        setOrderStateLog($find['id'], 'Canceled');
        // TODO: 这里还要执行退款逻辑  给用户进行退款  技师无法取消订单

        $this->success('取消订单成功,但是未完成退款状态');
    }

    // 技师已出发
    public function setOut ()
    {
        $params = $this->request->param();
        $find = $this->model
            ->where([
                'id' => $params['id']
            ])
            ->find();
        if (!$find) {
            $this->error("订单异常");
        }
        if ($find['order_state'] != "Received") {
            $this->error("订单异常");
        }
        if (empty($params['technician_lng']) || empty($params['technician_lat'])) {
            $this->error("参数错误");
        }
        // $area = \local\Area::lnglat($params['lng'],$params['lat']);
        $address = \local\Area::lnglat($params['technician_lng'], $params['technician_lat']);
        $find->order_state = 'SetOut';
        $find->technician_lng = $params['technician_lng'];
        $find->technician_lat = $params['technician_lat'];
        $find->technician_address = $address['result']['formatted_address'];

        $find->save();
        setOrderStateLog($find['id'], 'SetOut');
        $this->success('上门中..');
    }

    // 技师点击已到达
    public function reach ()
    {
        $params = $this->request->param();
        $find = $this->model
            ->where([
                'id' => $params['id']
            ])
            ->find();
        if (!$find) {
            $this->error("订单异常");
        }
        if ($find['order_state'] != "SetOut") {
            $this->error("订单异常");
        }
        $find->order_state = 'Reach';
        $find->save();
        setOrderStateLog($find['id'], 'Reach');
        $this->success('技师已到达');
    }

    /**
     * 技师点击开始服务
     */
    public function start ()
    {
        $params = $this->request->param();
        $find = $this->model
            ->where([
                'id' => $params['id']
            ])
            ->find();
        if (!$find) {
            $this->error("订单异常");
        }

        if ($find['order_state'] != 'Reach') {
            $this->error("订单异常");
        }

        $find->order_state = 'Start';
        $find->save();
        setOrderStateLog($find['id'], 'Start');
        $this->success('开始服务中');
    }

    // 完成订单
    public function completed ()
    {
        $params = $this->request->param();
        $orderInfo = $this->model
            ->where([
                'id' => $params['id']
            ])
            ->find();
        if (!$orderInfo) {
            $this->error("订单异常");
        }
        if ($orderInfo['order_state'] != 'Start') {
            $this->error("订单异常");
        }

        $time = Db::table("ba_config")
            ->where([
                "name" => "complete_time"
            ])
            ->value("value");


        $orderInfo->order_state = 'tchEnd';
        $orderInfo->tchend_time = date("Y-m-d H:i:s", time() + intval($time));
        $orderInfo->save();

        // #查询技师最新的余额表更
        // $technicianMoneyLog = Db::name('technician_money_log')->where('technician_id', $orderInfo->technician_id)->order('create_time', 'desc')->find();
        // if ($orderInfo->type == 2) {
        //     #加钟订单
        //     #获取系统规定的加钟提成比例
        //     $service_distribution_rebate = get_sys_config('add_clock_rebate') ?? 50;
        //     #计算技师的分成
        //     $distribution_rebate_decimal = bcdiv((string)$service_distribution_rebate, (string)100, 2);
        //     $money = bcmul($orderInfo->service_reality_price, $distribution_rebate_decimal, 2);
        // } else {
        //     #正常订单
        //     #服务返佣比例
        //     $service_distribution_rebate = \app\admin\model\service\Service::where('service_id', $orderInfo->service_id)->value('distribution_rebate') ?? 0;
        //     #计算技师的分成  $orderInfo->service_reality_price * $service_distribution_rebate
        //     $distribution_rebate = bcdiv((string)$service_distribution_rebate, (string)100, 2);
        //     $money = bcmul($orderInfo->service_reality_price, $distribution_rebate, 2);
        //     #给技师加服务单数
        //     $technician = \app\admin\model\Technician::where('technician_id', $orderInfo->technician_id)->find();
        //     #现有服务单数+服务总单数
        //     $technician->service_order_num = $technician->service_order_num + $orderInfo->service_num;
        //     $technician->save();
        // }
        // $afterMoney = $technicianMoneyLog['after'] ?? 0;

        // Db::table("ba_technician_money_log")
        // ->insert([
        //     'technician_id' =>  $this->auth->technician_id,
        //     'money' =>  $money,
        //     'before'    =>  $this->auth->money,
        //     'after'     =>  bcadd($afterMoney, $money, 2),
        //     'memo'      =>  '订单完成,技师加余额',
        //     'create_time'   =>  date("Y-m-d H:i:s",time()),
        //     'type'  =>  1,
        //     'order_id'  =>  $orderInfo->id,
        // ]);


        // // 加余额
        // // service_reality_price
        // $this->auth->getTechnician()->inc('money', $money)->update();


        setOrderStateLog($orderInfo['id'], 'tchEnd');
        $this->success('订单已完成');
    }

    // 订单列表
    public function orderList (): void
    {
        $params = $this->request->param();
        $where = [];
        $where['technician_id'] = $this->auth->technician_id;
        if (!empty($params['order_state']) && $params['order_state'] != 'all') {

            $where['order_state'] = explode(',', $params['order_state']);
        }
        $rows = $this->model
            ->where($where)
            ->where([
                ['order_state', 'in', ['Received', 'SetOut', 'Reach', 'Completed', 'Start', 'tchEnd']],
                // ['order_state','=','SetOut'],
                // ['order_state','=','Reach'],
                // ['order_state','=','Completed'],
            ])
            ->with(['service', 'fareorder'])
            ->order("id", 'desc')
            ->paginate(10)
            ->visible(['id', 'service_id', 'technician_id', 'service_start_time', 'service_total_price', 'service_price', 'service_num', 'service_reality_price', 'order_state', 'address_tel', 'address_username',
                'service.service_name', 'type', 'fareorder.fare_fare_price_imgs'])
            ->append(['order_state_text']);
        $this->success("", $rows);
    }


    /**
     * 订单详情
     */
    public function orderInfo ()
    {
        $params = $this->request->param();
        $where = [];
        $where['technician_id'] = $this->auth->technician_id;
        $where['id'] = $params['order_id'];
        $row = $this->model
            ->where($where)
            ->with(['service', 'fareorder'])
            ->find()
            ->append(['service.service_cover_img_text']);

        $row->service_total_price = bcsub($row->service_reality_price, $row->fare_price, 2);
        $this->success("", $row);
    }


    /**
     * 实时记录技师的经纬度
     */
    public function lnglat ()
    {
        $params = $this->request->param();

        $validate = \think\facade\Validate::rule([
            'order_id|订单数据' => 'require',
            'lng|经度'          => 'require',
            'lat|纬度'          => 'require',
        ]);

        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $params['create_time'] = date("Y-m-d H:i:s", time());
        $save = Db::table("ba_lnglat")
            ->save($params);
        if ($save) {
            $this->success("位置更新成功");
        }
        $this->error("位置更新失败");
    }

    /**
     * 查询是否有进行中的订单
     */
    public function getlnglatOrder ()
    {
        $params = $this->request->param();
        $rows = $this->model
            ->where([
                'order_state'   => 'SetOut',
                'technician_id' => $this->auth->technician_id
            ])
            ->order("payment_time", 'desc')
            ->find();
        if (!$rows) {
            $this->error("没有相关的订单信息");
        }
        $this->success("正在进行的订单", $rows);
    }


}